package it.fuesi.synotools.fragments;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.DataSetObserver;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import java.util.Set;

import it.fuesi.synotools.R;
import it.fuesi.synotools.activities.FileStationFileDetailActivity;
import it.fuesi.synotools.activities.MainActivity;
import it.fuesi.synotools.adapters.FileStationFilesAdapter;
import it.fuesi.synotools.helpers.FormatHelper;
import it.fuesi.synotools.model.filestation.FileStationClientParameters;
import it.fuesi.synotools.model.filestation.FileStationFile;
import it.fuesi.synotools.services.cache.CacheService;
import it.fuesi.synotools.services.tasks.filestation.AddFolder;
import it.fuesi.synotools.services.tasks.filestation.DeleteFile;
import it.fuesi.synotools.services.tasks.filestation.FileStationList;
import it.fuesi.synotools.services.tasks.filestation.CopyFile;
import it.fuesi.synotools.services.tasks.filestation.RenameFile;


/**
 * A simple {@link android.app.Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link it.fuesi.synotools.fragments.FileStationFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link it.fuesi.synotools.fragments.FileStationFragment#newInstance} factory method to
 * create an instance of this fragment.
 *
 */
public class FileStationFragment extends BaseFragment implements FileStationFilesAdapter.OnItemChecked {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_SECTION_NUMBER = "section_number";
    private static final String TAG = "FileStationFragment";


    // TODO: Rename and change types of parameters
    private int mSectionNumber;

    private OnFragmentInteractionListener mListener;

    private ListView mTasks;
    private FileStationFilesAdapter mAdapter;
    private ImageButton mBtnParentFolder;
    private TextView mCurrentFolder;

    private TextView mTotalFolder;
    private TextView mTotalFiles;
    private TextView mTotalSize;

    private LinearLayout mMsgLayout;
    private TextView mMsgText;

    private boolean moving = false;
    private boolean copying = false;


    @Override
    public boolean onBackPressed() {
        final String parentFolderPath = mAdapter.goToParent();
        return true;
    }


    @Override
    public void onActionRefresh() {
        Log.d(TAG, "onActionRefresh --> ");
        final FileStationClientParameters params = FileStationClientParameters.build(true);
        params.setFolder_path(mAdapter.getCurrentFolder());
        CacheService.expireCache(getActivity(), FileStationList.CACHE_KEY_PREFIX + params.getFolder_path());
        mAdapter.fetch(params);
    }

    public void setCurrentFolder(String currentFolder){
        mAdapter.setCurrentFolder(currentFolder);
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     *
     * @return A new instance of fragment DownloadStationFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static FileStationFragment newInstance(int position) {
        FileStationFragment fragment = new FileStationFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, position);
        fragment.setArguments(args);
        return fragment;
    }
    public FileStationFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mSectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
        }



    }


    private Menu mActivityMenu;

    protected void toggleMenuItem(int itemId, boolean visible){
        if(mActivityMenu == null) return;

        MenuItem item = mActivityMenu.findItem(itemId);

        if(item != null)
            item.setVisible(visible);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        final View rootView = inflater.inflate(R.layout.fragment_file_station, container, false);

        mTasks = (ListView)rootView.findViewById(R.id.file_list);

        mAdapter = new FileStationFilesAdapter(inflater,null, this.getActivity(), this);

        mTotalFolder = (TextView)rootView.findViewById(R.id.dir_total_folders);
        mTotalFiles = (TextView)rootView.findViewById(R.id.dir_total_files);
        mTotalSize = (TextView)rootView.findViewById(R.id.dir_total_size);

        mMsgLayout = (LinearLayout)rootView.findViewById(R.id.msg_layout);
        mMsgLayout.setVisibility(View.GONE);
        mMsgText = (TextView)rootView.findViewById(R.id.msg_text);

        mActivityMenu = ((MainActivity)getActivity()).getMenu();

        mAdapter.registerDataSetObserver(new DataSetObserver() {
            @Override
            public void onChanged() {
                super.onChanged();

                mTasks.scrollTo(0,0);

                mTotalFolder.setText(""+mAdapter.getFolders());
                mTotalFiles.setText(""+mAdapter.getFiles());
                mTotalSize.setText(FormatHelper.formatFileSize(mAdapter.getTotalSize()));

                mCurrentFolder.setText(FormatHelper.formatBreadCrumb(mAdapter.getCurrentFolder()));

                manageCurrentFolderButtons(mAdapter.getCurrentFolder());


            }
        });

        mAdapter.setOnItemCheckedEventListener(this);

        mTasks.setAdapter(mAdapter);

        mTasks.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                final FileStationFile file = (FileStationFile)mAdapter.getItem(i);
                if(file.isdir()) {
                    FileStationClientParameters params = FileStationClientParameters.build(false);
                    params.setFolder_path(file.getPath());
                    mAdapter.fetch(params);
                }else{
                    Intent intent = new Intent(getActivity(), FileStationFileDetailActivity.class);
                    intent.putExtra(FileStationFileDetailActivity.EXTRA_DETAIL_ITEM, file);
                    startActivityForResult(intent, FileStationFileDetailActivity.REQUEST_CODE);
                }
            }
        });

        mTasks.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                toggleSelectionMode();

                return true;
            }
        });


        mCurrentFolder = (TextView)rootView.findViewById(R.id.current_folder_path);

        mBtnParentFolder = (ImageButton)rootView.findViewById(R.id.btn_parent_folder);
        mBtnParentFolder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String parentFolderPath = mAdapter.goToParent();
            }
        });




        return rootView;
    }

    private void manageCurrentFolderButtons(String currentFolder){
        if(currentFolder == null || currentFolder.isEmpty() || currentFolder.equals("/")){
            toggleMenuItem(R.id.action_select,false);
            toggleMenuItem(R.id.action_rename,false);
            toggleMenuItem(R.id.action_add,false);
        }else{
            toggleMenuItem(R.id.action_select,true);
            toggleMenuItem(R.id.action_rename,true);
            toggleMenuItem(R.id.action_add,true);
        }
    }


    @Override
    public void onOptionsMenuRefreshed() {
        super.onOptionsMenuRefreshed();

        if(mAdapter != null && mAdapter.isSelectionMode())
            enableSelectionMode();
        else
            disableSelectionMode();

        manageCurrentFolderButtons(mAdapter == null ? null : mAdapter.getCurrentFolder());

        if(copying){
            toggleMenuItem(R.id.action_accept, true);
            toggleMenuItem(R.id.action_cancel, true);
            toggleMenuItem(R.id.action_select, false);
        }

    }

    private void enableSelectionMode(){
        mAdapter.setSelectionMode(true);
        mAdapter.notifyDataSetChanged();
        toggleMenuItem(R.id.action_move,true);
        toggleMenuItem(R.id.action_copy,true);
        toggleMenuItem(R.id.action_delete,true);
        toggleMenuItem(R.id.action_rename,false);
        toggleMenuItem(R.id.action_select,false);
    }

    private void disableSelectionMode(){
        mAdapter.setSelectionMode(false);
        mAdapter.notifyDataSetChanged();
        toggleMenuItem(R.id.action_move,false);
        toggleMenuItem(R.id.action_copy,false);
        toggleMenuItem(R.id.action_delete,false);
        toggleMenuItem(R.id.action_rename,true);
        toggleMenuItem(R.id.action_select,true);
        hideMsg();
    }

    private void toggleSelectionMode(){
        if(mAdapter.isSelectionMode())
            disableSelectionMode();
        else
            enableSelectionMode();
    }

    @Override
    public void onItemChecked() {
        setMsg(mAdapter.getSelections().size() + " " + getString(R.string.items_selected));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_move) {
            prepareCopy(true);
            return true;
        }else if (id == R.id.action_copy) {
            prepareCopy(false);
            return true;
        }else if(id == R.id.action_accept){
            copyFiles();
            return true;
        }else if(id == R.id.action_cancel){
            cancelCopying();
            return true;
        }else if(id == R.id.action_add){
            prepareAddFolder();
            return true;
        }else if(id == R.id.action_select){
            toggleSelectionMode();
            return true;
        }else if(id == R.id.action_rename){
            prepareRenameFolder();
            return true;
        }else if(id == R.id.action_delete){
            prepareDelete();
            return true;
        }

        return false;
    }

    private void prepareRenameFolder(){
        if(mAdapter.getCurrentFolder().lastIndexOf("/")==0){
            new AlertDialog.Builder(getActivity())
                    .setTitle(getString(R.string.rename_shared_fail_title))
                    .setMessage(getString(R.string.rename_shared_fail_msg))
                    .setNegativeButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .show();
            return;
        }
        final EditText edit = new EditText(getActivity());
        edit.setText(mAdapter.getCurrentFolderName());
        edit.setSelectAllOnFocus(true);
        new AlertDialog.Builder(getActivity())
                .setTitle(getString(R.string.rename_folder_title))
                .setView(edit)
                .setMessage(getString(R.string.rename_folder_msg))
                .setPositiveButton(getString(R.string.rename), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        renameFolder(edit.getText().toString());
                    }
                })
                .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_info)
                .show();
    }

    private void renameFolder(String newFolderName){
        FileStationClientParameters params = new FileStationClientParameters();
        params.setFile_path(mAdapter.getCurrentFolder());
        params.setName(newFolderName);
        params.setFolder_path(mAdapter.getCurrentFolderParent());

        new RenameFile(getActivity()).execute(params);
    }

    private void prepareAddFolder(){
        if(mAdapter.getCurrentFolder() == null || mAdapter.getCurrentFolder().equals("/")){
            new AlertDialog.Builder(getActivity())
                    .setTitle(getString(R.string.create_folder_fail_title))
                    .setMessage(getString(R.string.create_folder_fail_msg))
                    .setNegativeButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .show();
            return;
        }

        final EditText edit = getInputText(getString(R.string.create_folder_text));


       // final InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        //imm.showSoftInput(edit, InputMethodManager.SHOW_IMPLICIT);
        new AlertDialog.Builder(getActivity())
                .setTitle(getString(R.string.create_folder_title))
                .setView(edit)
                .setMessage(getString(R.string.create_folder_msg))
                .setPositiveButton(getString(R.string.create), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        addFolder(edit.getText().toString());
                    }
                })
                .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_info)
                .show();
    }

    private void addFolder(String folderName){
        final FileStationClientParameters params = new FileStationClientParameters();
        final String parentPath = mAdapter.getCurrentFolder();
        params.setFolder_path(parentPath);
        params.setName(folderName);

        new AddFolder(getActivity()).execute(params);

    }



    private void cancelCopying(){
        doneCopying(false);
    }

    private void copyFiles(){
        Log.d(TAG, "Copying files to --> " + mAdapter.getCurrentFolder() + " - move["+moving+"]");
        FileStationClientParameters params = new FileStationClientParameters();
        params.setFolder_path(mAdapter.getCurrentFolder());
        params.addToFilePath(selections);
        params.setRemove_src(moving);

        new CopyFile(getActivity()).execute(params);
    }

    public void doneCopying(boolean refresh){
        MainActivity main = (MainActivity)getActivity();
        toggleMenuItem(R.id.action_accept, false);
        toggleMenuItem(R.id.action_cancel, false);
        toggleMenuItem(R.id.action_select, true);

        copying = false;
        moving = false;
        hideMsg();
        selections = null;


        if(refresh) {
            onActionRefresh();
        }



    }

    private void setMsg(String msg){
        if(mMsgLayout.getVisibility() != View.VISIBLE)
            mMsgLayout.setVisibility(View.VISIBLE);

        mMsgText.setText(msg);
    }

    private void hideMsg(){
        mMsgLayout.setVisibility(View.GONE);
    }


    private Set<String> selections;


    private boolean deleting = true;

    private void prepareDelete(){
        if(mAdapter.getSelections().size() == 0){
            disableSelectionMode();
            doneDeleting(false);
            return;
        }
        deleting = true;
        selections = mAdapter.getSelections();
        disableSelectionMode();

        new AlertDialog.Builder(getActivity())
                .setTitle(getString(R.string.confirm_delete_title))
                .setMessage(getString(R.string.confirm_delete_msg).replaceAll("#N#", ""+selections.size()))
                .setPositiveButton(getString(R.string.delete), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        deleteFiles();
                    }
                })
                .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_info)
                .show();

    }

    public void doneDeleting(boolean refresh){
        MainActivity main = (MainActivity)getActivity();
        deleting = false;
        hideMsg();
        selections = null;

        if(refresh) {
            onActionRefresh();
        }
    }

    private void deleteFiles(){
        FileStationClientParameters params = new FileStationClientParameters();
        params.addToFilePath(selections);
        params.setFolder_path(mAdapter.getCurrentFolder());
        new DeleteFile(getActivity()).execute(params);
    }



    private void prepareCopy(boolean move){
        if(mAdapter.getSelections().size() == 0){
            disableSelectionMode();
            doneCopying(false);
            return;
        }

        copying = true;
        moving = move;
        selections = mAdapter.getSelections();
        setMsg((move ? getString(R.string.moving) : getString(R.string.copying)) + " " + selections.size() + " " +getString(R.string.files));
        disableSelectionMode();
        MainActivity main = (MainActivity)getActivity();
        toggleMenuItem(R.id.action_accept, true);
        toggleMenuItem(R.id.action_cancel, true);
    }



    @Override
    public void onStart() {
        super.onStart();

        Log.d(TAG, "OnStart --> ");

        mAdapter.fetch();
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;

        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }

            ((MainActivity) activity).onSectionAttached(
                    getArguments().getInt(ARG_SECTION_NUMBER));
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }




}
